<?php

class CategoryManager extends Manager
{
	const TABLE_NAME = 'kategorie';
	const OBJECT_NAME = 'Category';

	public function getById($id)
	{
		$select = $this->_db->select()->from(self::TABLE_NAME)
					->where('id = ?', $id);
		$result = $this->_db->fetchRow($select);
		return $this->_createObject(self::OBJECT_NAME, $result);
	}
	
	public function getRoot()
	{
		$select = $this->_db->select()->from(self::TABLE_NAME)
					->where('level = ?', 0);
		$result = $this->_db->fetchRow($select);
		return $this->_createObject(self::OBJECT_NAME, $result);
	}
	
	public function getDescendants(Category $category)
	{
		$select = $this->_db->select()->from(self::TABLE_NAME)
					->where('lft > ?', $category->lft)
					->where('rgt < ?', $category->rgt)
					->order('lft asc');
		$result = $this->_db->fetchAll($select);
		return $this->_createCollection(self::OBJECT_NAME, $result);
	}
	
	public function getChildren(Category $category)
	{
		$select = $this->_db->select()->from(self::TABLE_NAME)
					->where('lft > ?', $category->lft)
					->where('rgt < ?', $category->rgt)
					->where('level = ?', $category->level + 1)
					->order('lft asc');
		$result = $this->_db->fetchAll($select);
		return $this->_createCollection(self::OBJECT_NAME, $result);
	}
	
	public function deleteBranch(Category $category)
	{
		foreach ($category->getDescendants() as $c) {
			$this->delete($c);
		}
		$this->delete($category);
	}
	
}